<template>
  <div class="network-basic">
    <a-form ref="formRef" :model="formState" layout="vertical">
      <a-card title="网络模式" :bordered="false">
        <a-form-item name="networkMode">
          <a-radio-group v-model:value="formState.networkMode" button-style="solid">
            <a-radio-button value="dhcp">DHCP</a-radio-button>
            <a-radio-button value="static">静态IP</a-radio-button>
          </a-radio-group>
        </a-form-item>

        <template v-if="formState.networkMode === 'static'">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item 
                label="IP地址" 
                name="ipAddress" 
                :rules="[
                  { required: true, message: '请输入IP地址' },
                  { validator: validateIP }
                ]"
              >
                <a-input v-model:value="formState.ipAddress" placeholder="192.168.1.100" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item 
                label="子网掩码" 
                name="subnetMask" 
                :rules="[
                  { required: true, message: '请输入子网掩码' },
                  { validator: validateSubnetMask }
                ]"
              >
                <a-input v-model:value="formState.subnetMask" placeholder="255.255.255.0" />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item 
                label="默认网关" 
                name="gateway" 
                :rules="[
                  { required: true, message: '请输入默认网关' },
                  { validator: validateIP }
                ]"
              >
                <a-input v-model:value="formState.gateway" placeholder="192.168.1.1" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item 
                label="首选DNS" 
                name="primaryDNS" 
                :rules="[{ validator: validateDNS }]"
              >
                <a-input v-model:value="formState.primaryDNS" placeholder="8.8.8.8" />
              </a-form-item>
            </a-col>
          </a-row>

          <a-form-item 
            label="备选DNS" 
            name="secondaryDNS"
            :rules="[{ validator: validateDNS }]"
          >
            <a-input v-model:value="formState.secondaryDNS" placeholder="8.8.4.4" />
          </a-form-item>
        </template>
      </a-card>

      <div style="margin-top: 16px">
        <a-space>
          <a-button type="primary" @click="handleSubmit" :loading="loading">保存设置</a-button>
          <a-button @click="handleReset">重置</a-button>
        </a-space>
      </div>
    </a-form>
  </div>
</template>

<script>
import { defineComponent, reactive, ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { getNetworkConfig, configureNetwork, updateDnsServers } from '@/api/network';

export default defineComponent({
  name: 'NetworkBasic',
  setup() {
    // IP地址验证函数
    const validateIP = (rule, value) => {
      if (!value) {
        return Promise.reject('请输入IP地址');
      }
      
      const ipPattern = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
      
      if (!ipPattern.test(value)) {
        return Promise.reject('请输入有效的IP地址');
      }
      
      return Promise.resolve();
    };

    // 子网掩码验证函数
    const validateSubnetMask = (rule, value) => {
      if (!value) {
        return Promise.reject('请输入子网掩码');
      }
      
      const maskPattern = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
      
      if (!maskPattern.test(value)) {
        return Promise.reject('请输入有效的子网掩码');
      }
      
      return Promise.resolve();
    };

    // DNS验证函数（可选）
    const validateDNS = (rule, value) => {
      if (!value) {
        return Promise.resolve(); // DNS 可以为空
      }
      
      const dnsPattern = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/;
      
      if (!dnsPattern.test(value)) {
        return Promise.reject('请输入有效的DNS地址');
      }
      
      return Promise.resolve();
    };
    const defaultSettings = {
      networkMode: 'dhcp',
      ipAddress: '',
      subnetMask: '',
      gateway: '',
      primaryDNS: '',
      secondaryDNS: ''
    };

    const formState = reactive({ ...defaultSettings });
    const loading = ref(false);
    const defaultInterfaceName = ref('eth0');
    const formRef = ref(null);

    const fetchNetworkConfig = async () => {
      try {
        loading.value = true;
        const response = await getNetworkConfig();
        
        if (response?.result) {
          // 获取默认接口配置
          defaultInterfaceName.value = response.result.default_interface || 'eth0';
          const interfaceConfig = response.result.interfaces[defaultInterfaceName.value];

          if (interfaceConfig) {
            // 更新表单状态
            formState.networkMode = interfaceConfig.mode || 'dhcp';

            if (formState.networkMode === 'static' && interfaceConfig.ipv4) {
              formState.ipAddress = interfaceConfig.ipv4.address || '';
              formState.subnetMask = interfaceConfig.ipv4.netmask || '';
              formState.gateway = interfaceConfig.ipv4.gateway || '';
            }

            // 设置DNS配置
            if (response.result.dns && Array.isArray(response.result.dns)) {
              if (response.result.dns.length > 0) {
                formState.primaryDNS = response.result.dns[0] || '';
              }
              if (response.result.dns.length > 1) {
                formState.secondaryDNS = response.result.dns[1] || '';
              }
            }
          }
        }
      } catch (error) {
        console.error('获取网络配置失败:', error);
        message.error('获取网络配置失败，请刷新页面重试');
      } finally {
        loading.value = false;
      }
    };

    const handleSubmit = async () => {
      try {
        // 先进行表单验证
        await formRef.value.validate();
        
        loading.value = true;

        // 构建请求数据
        const params = {
          interface_name: defaultInterfaceName.value,
          enable: true,
          mode: formState.networkMode
        };

        // 静态IP模式下需要添加IP配置
        if (formState.networkMode === 'static') {
          params.ipv4 = {
            address: formState.ipAddress,
            netmask: formState.subnetMask,
            gateway: formState.gateway
          };
        }

        // 无论是什么模式，如果有DNS配置，都更新DNS
        if (formState.primaryDNS || formState.secondaryDNS) {
          const dnsServers = [];
          if (formState.primaryDNS) {
            dnsServers.push(formState.primaryDNS);
          }
          if (formState.secondaryDNS) {
            dnsServers.push(formState.secondaryDNS);
          }
          
          // 先更新网络配置
          await configureNetwork(params);
          
          // 然后更新DNS配置
          const dnsResponse = await updateDnsServers(dnsServers);
          
          if (dnsResponse?.result?.requires_reboot) {
            message.success('网络设置已保存，需要重启设备以使配置生效');
          } else {
            message.success('网络设置已保存');
          }
        } else {
          // 如果没有DNS配置，只更新网络配置
          const response = await configureNetwork(params);
          
          if (response?.result?.requires_reboot) {
            message.success('网络设置已保存，需要重启设备以使配置生效');
          } else {
            message.success('网络设置已保存');
          }
        }
      } catch (error) {
        console.error('保存网络设置失败:', error);
        if (error.errorFields) {
          // 表单验证失败
          message.error('请检查输入的网络配置信息');
        } else {
          message.error('保存失败: ' + (error.message || '请重试'));
        }
      } finally {
        loading.value = false;
      }
    };

    const handleReset = () => {
      Object.assign(formState, defaultSettings);
      message.info('已重置为默认设置');
    };

    // 组件挂载时获取网络配置
    onMounted(() => {
      fetchNetworkConfig();
    });

    return {
      formState,
      loading,
      formRef,
      validateIP,
      validateSubnetMask,
      validateDNS,
      handleSubmit,
      handleReset
    };
  }
});
</script>

<style scoped>
.network-basic {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}
</style>
